<?php
declare(strict_types=1);

namespace Service\CommodityService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\GoodsManagerTags;
use App\Model\BbcModel\Storage;
use App\Model\BbcModel\ConfigChannel;
use App\Model\BbcModel\GoodsBrand;
use App\Model\BbcModel\Goodscommon;
use App\Model\BbcModel\GoodsSupplyClass;
use App\Model\BbcModel\GoodsService;
use App\Model\BbcModel\TransitTemplate;
use App\Model\BbcModel\GoodsSpecPrice;
use App\Model\BbcModel\GoodsBatch;
use App\Model\BbcModel\DistributorPrice;
use App\Model\BbcModel\DistributorLevel;
use Service\ExportService\ExportExcelHandle;

/**
 * 渠道商品服务-前置仓商品
 * @author huj
 */
class ChannelCommoditySpService extends BaseService {
    /**
     * 前置仓商品列表
     * @param array $param
     */
    public function goodsList(array $param) {
        $param['sp'] = 1;
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        $whereRaw = ChannelCommodityCommonService::instance()->handleWhere($param);
        $sortRaw  = ChannelCommodityCommonService::instance()->handleSort($param);
        $fields   = [
            'id', 'img', 'name', 'barcode', 'skucode', 'class_id', 'brand_id', 'num_sale', 'month_sale', 'is_high_goods', 'high_tax_rate',
            'stoid', 'tax_free', 'high_price', 'tax_rate', 'is_update', 'status', 'price_store', 'manager_tag', 'num_storage', 'warn_storage',
            'is_bonded', 'is_trade', 'price_cost', 'price_market', 'show_order', 'up', 'price_recommend', 'price_recommend_vip', 'cd', 'medicinal',
            'isfree_postfee', 'supplier_name', 'weight', 'origin', 'supply_class_id', 'service_id', 'template_id', 'buy_limit', 'type', 'is_price_cost_change'
        ];
        $result   = Goods::select($fields)->where('is_trade', 0)->whereRaw($whereRaw)->orderByRaw($sortRaw)->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功', [
                'onLineCount'  => 0,//已上架商品数
                'offLineCount' => 0,//已下架商品数
                'allCount'     => 0,//总商品数
                'newCount'     => 0,//新品待上架商品数
                'riskCount'    => 0,//风控下架商品数
                'manualCount'  => 0,//手动下架商品数
                'list'         => [],
                'total'        => 0,
            ]);
        }
        $collection = $result->getCollection();
        $goods_ids  = $collection->pluck('id')->toArray();
        $goodsSpec  = GoodsSpecPrice::whereIn('goods_id', $goods_ids)->get()->toArray();
        $specBygid  = [];
        if ($goodsSpec) {
            foreach ($goodsSpec as $spec) {
                $specBygid[$spec['goods_id']][] = $spec;
            }
        }
        $tagArr     = GoodsManagerTags::where('cid', $param['cid'])->where('df', 0)->pluck('name', 'id')->toArray();
        $storageArr = Storage::where('cid', 0)->where('df', 0)->pluck('desc', 'id')->toArray();
        $payRate    = ConfigChannel::instance()->getPayFee(['cid' => $param['cid']]);
        $class_ids  = $collection->pluck('class_id')->toArray();
        $allClass   = GoodsClass::whereIn('id', $class_ids)->pluck('name', 'id')->toArray();
        $brand_ids  = $collection->pluck('brand_id')->toArray();
        $allBrand   = GoodsBrand::whereIn('id', $brand_ids)->pluck('name', 'id')->toArray();
        $sclass_ids = $collection->pluck('supply_class_id')->toArray();
        $sclassArr  = GoodsSupplyClass::whereIn('id', $sclass_ids)->pluck('name', 'id')->toArray();
        $serviceArr = GoodsService::where('cid', $param['cid'])->where('status', 1)->pluck('title', 'id')->toArray();
        $tplArr     = TransitTemplate::where('cid', $param['cid'])->where('df', 0)->pluck('name', 'id')->toArray();
        $collection->each(function ($item, $key) use ($tagArr, $storageArr, $payRate, $allClass, $allBrand, $sclassArr, $serviceArr, $tplArr, $specBygid) {
            $specArr = $specBygid[$item->id] ?? [];
            $newSpec = [];
            foreach ($specArr as $spec) {
                $costUnitPrice            = bcdiv((string)($spec['price_cost']), (string)($spec['spec_num']), 2);//成本单价
                $settlementUnitPrice      = bcdiv((string)($spec['price_store']), (string)($spec['spec_num']), 2);//结算单价
                $costUnitPricNoTax        = $costUnitPrice;//不含税成本单价
                $settlementUnitPriceNoTax = $settlementUnitPrice;//不含税结算单价
                if ($item->is_bonded == 1 && $item->tax_free == 1) {
                    if ($item->high_price > 0) {
                        $pricestoretax_rate = $item->tax_rate;
                        $pricecosttax_rate  = $item->tax_rate;
                        if ($settlementUnitPrice >= $item->high_price) {
                            $pricestoretax_rate = $item->high_tax_rate;
                        }
                        if ($costUnitPrice >= $item->high_price) {
                            $pricecosttax_rate = $item->high_tax_rate;
                        }
                        $settlementUnitPriceNoTax = round(($settlementUnitPrice / (1 + $pricestoretax_rate)), 2);
                        $costUnitPricNoTax        = round($costUnitPrice / (1 + $pricecosttax_rate), 2);
                    } else {
                        $settlementUnitPriceNoTax = round($settlementUnitPrice / (1 + $item->tax_rate), 2);
                        $costUnitPricNoTax        = round($costUnitPrice / (1 + $item->tax_rate), 2);
                    }
                }
                $unitProfit      = bcsub((string)$settlementUnitPriceNoTax, (string)$costUnitPricNoTax, 2);
                $unitProfitTotal = bcmul($unitProfit, (string)($spec['spec_num']), 2);
                $newSpec[]       = [
                    'spec_num'               => $spec['spec_num'],
                    'price_market'           => $spec['price_market'],
                    'price_recommend'        => $spec['price_recommend'],
                    'price_recommend_vip'    => $spec['price_recommend_vip'],
                    'high_price'             => bcmul((string)($spec['spec_num']), (string)($item->high_price), 2),//含税预警价
                    'cost_price_total'       => $costUnitPrice . '/' . $spec['price_cost'],
                    'settlement_price_total' => $settlementUnitPrice . '/' . $spec['price_store'],
                    'unit_profit_total'      => round($unitProfit * $payRate, 2) . '/' . round($unitProfitTotal * $payRate, 2),//单件利润小计算
                ];
            }
            $item->goods_spec      = $newSpec;
            $item->settlement_type = Goods::$settlementType[$item->type] ?? '';
            $item->class_text      = $allClass[$item->class_id] ?? '';
            $item->brand_text      = $allBrand[$item->brand_id] ?? '';
            $item->template        = $tplArr[$item->template_id] ?? '';
            $item->status_text     = Goods::$status[$item->status] ?? '';
            $item->has_storage     = $item->num_storage > 0 ? '是' : '否';
            $item->storage_name    = $storageArr[$item->stoid] ?? '';
            $item->has_price       = $item->price_store > 0 ? '是' : '否';
            $item->is_high         = $item->is_high_goods > 0 ? '已触发消费税' : '';
            $item->is_price_wrong  = "否";
            if ($item->price_recommend_vip > $item->price_recommend || $item->price_recommend < $item->price_store || $item->price_recommend_vip < $item->price_store || $item->price_cost > $item->price_store) {
                $item->is_price_wrong = "是";
            }
            if (!empty($item->manager_tag)) {
                $tag    = explode(',', $item->manager_tag);
                $tagStr = '';
                foreach ($tag as $v) {
                    if (isset($tagArr[$v])) {
                        $tagStr .= $tagArr[$v] . ',';
                    }
                }
                if (!empty($tagStr)) {
                    $item->manager_tag = rtrim($tagStr, ',');
                } else {
                    $item->manager_tag = '';
                }
            }
            $item->cd = date('Y-m-d H:i:s', $item->cd);
            //预估利润
            if ($item->is_bonded == 1 && $item->tax_free == 1) {
                if ($item->high_price > 0) {
                    $pricestoretax_rate = $item->tax_rate;
                    $pricecosttax_rate  = $item->tax_rate;
                    if ($item->price_store >= $item->high_price) {
                        $pricestoretax_rate = $item->high_tax_rate;
                    }
                    if ($item->price_cost >= $item->high_price) {
                        $pricecosttax_rate = $item->high_tax_rate;
                    }
                    $item->except_money = round(($item->price_store / (1 + $pricestoretax_rate) - $item->price_cost / (1 + $pricecosttax_rate)) * $payRate, 2);
                } else {
                    $item->except_money = round(($item->price_store / (1 + $item->tax_rate) - $item->price_cost / (1 + $item->tax_rate)) * $payRate, 2);
                }
            } else {
                $item->except_money = round(($item->price_store - $item->price_cost) * $payRate, 2);
            }
            $item->is_bonded         = Goodscommon::$is_bonded[$item['is_bonded']] ?? '';
            $item->weight            = $item->weight . '克';
            $item->supply_class_text = $sclassArr[$item->supply_class_id] ?? '';
            //$serviceArr   service_id
            $item->service_text = '';
            if (!empty($item->service_id)) {
                $service_ids    = explode(',', $item->service_id);
                $serviceTextArr = [];
                foreach ($service_ids as $serid) {
                    if (isset($serviceArr[$serid])) {
                        array_push($serviceTextArr, $serviceArr[$serid]);
                    }
                }
                $item->service_text = $serviceTextArr ? implode(',', $serviceTextArr) : '';
            }
            return $item;
        });
        //设置商品数目
        $goodsCountFields = ['id', 'status', 'down_status'];
        $goodsQueryCount  = Goods::where('df', 0)->where('cid', $param['cid'])->where('is_trade', 0)->where('is_fast_delivery', 1)->select($goodsCountFields)->get()->toArray();
        $onLineCount      = 0;
        $offLineCount     = 0;
        $allCount         = 0;
        $newCount         = 0;
        $riskCount        = 0;
        $manualCount      = 0;
        foreach ($goodsQueryCount as $v) {
            if ($v['status'] == 1) {
                $onLineCount += 1;
            }
            if ($v['status'] == 0) {
                $offLineCount += 1;
            }
            if ($v['status'] == 0 && $v['down_status'] == 1) {
                $newCount += 1;
            }
            if ($v['status'] == 0 && $v['down_status'] == 2) {
                $riskCount += 1;
            }
            if ($v['status'] == 0 && $v['down_status'] == 0) {
                $manualCount += 1;
            }
        }
        $allCount = $onLineCount + $offLineCount;
        $data     = [
            'onLineCount'  => $onLineCount,//已上架商品数
            'offLineCount' => $offLineCount,//已下架商品数
            'allCount'     => $allCount,//总商品数
            'newCount'     => $newCount,//新品待上架商品数
            'riskCount'    => $riskCount,//风控下架商品数
            'manualCount'  => $manualCount,//手动下架商品数
            'list'         => $collection->toArray(),
            'total'        => $result->total(),
        ];
        return Normal::returnCode(Normal::SUC, "获取成功", $data);
    }

    /**
     * 批量设置上下架
     * @param array $param
     */
    public function setOnlineStatus(array $param) {
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['status']) || !in_array($param['status'], ['1', '0'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument status');
        }
        if (!isset($param['goods_ids']) || empty($param['goods_ids']) || !is_array($param['goods_ids'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument goods_ids');
        }
        $param['cid'] = (int)($param['cid']);
        $isTrade      = $param['is_trade'] ?? 0;
        $data         = ['status' => $param['status'], 'md' => time()];
        if ($param['status'] == 0) {
            $data['down_status'] = 0;
        }
        $model = Goods::whereIn('id', $param['goods_ids'])->where('cid', $param['cid'])->where('is_fast_delivery', 1)->where('is_trade', $isTrade);
        if ($param['status'] == 1 && $isTrade == 0) {
            $model = $model->whereRaw(" num_storage>0 and price_cost <= price_store and price_recommend>=price_store and price_recommend_vip>=price_store");
        }
        $model->update($data);
        //ES更新索引
        ChannelCommodityEsService::instance()->updateIndexByOnlineStatus($param, 1);
        return Normal::returnCode(Normal::SUC, '设置成功');
    }

    /**
     * 批量设置标签
     * @param array $param
     */
    public function setTag(array $param) {
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['tag_ids']) || empty($param['tag_ids']) || !is_array($param['tag_ids'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument tag_ids');
        }
        if (!isset($param['goods_ids']) || empty($param['goods_ids']) || !is_array($param['goods_ids'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument goods_ids');
        }
        $param['cid'] = (int)($param['cid']);
        $isTrade      = $param['is_trade'] ?? 0;
        $tagStr       = implode(',', $param['tag_ids']);
        Goods::whereIn('id', $param['goods_ids'])->where('cid', $param['cid'])->where('is_fast_delivery', 1)->where('is_trade', $isTrade)->update(['manager_tag' => $tagStr, 'md' => time()]);
        return Normal::returnCode(Normal::SUC, '设置成功');
    }

    /**
     * 批量设置商品服务
     * @param array $param
     */
    public function setService(array $param) {
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['service_ids']) || empty($param['service_ids']) || !is_array($param['service_ids'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument service_ids');
        }
        if (!isset($param['goods_ids']) || empty($param['goods_ids']) || !is_array($param['goods_ids'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument goods_ids');
        }
        $param['cid'] = (int)($param['cid']);
        $isTrade      = $param['is_trade'] ?? 0;
        $serviceStr   = implode(',', $param['service_ids']);
        Goods::whereIn('id', $param['goods_ids'])->where('cid', $param['cid'])->where('is_fast_delivery', 1)->where('is_trade', $isTrade)->update(['service_id' => $serviceStr, 'md' => time()]);
        return Normal::returnCode(Normal::SUC, '设置成功');
    }

    /**
     * 批量设置运费模板
     * @param array $param
     */
    public function setExpressTpl(array $param) {
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['template_id']) || empty($param['template_id'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument template_id');
        }
        if (!isset($param['goods_ids']) || empty($param['goods_ids']) || !is_array($param['goods_ids'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument goods_ids');
        }
        $param['cid'] = (int)($param['cid']);
        $tplId        = (int)($param['template_id']);
        $tpl          = TransitTemplate::where('id', $tplId)->where('cid', $param['cid'])->where('df', 0)->exists();
        if (empty($tpl)) {
            return Normal::returnCode(Normal::FAIL, "运费模板不存在");
        }
        $isTrade = $param['is_trade'] ?? 0;
        Goods::whereIn('id', $param['goods_ids'])->where('cid', $param['cid'])->where('is_fast_delivery', 1)->where('is_trade', $isTrade)->update(['template_id' => $tplId, 'md' => time()]);
        return Normal::returnCode(Normal::SUC, '设置成功');
    }

    /**
     * 批量设置限购数量
     * @param array $param
     */
    public function setBuyLimit(array $param) {
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['limit_num']) || empty($param['limit_num']) || (preg_match("/^[1-9]\d*$/", (string)$param['limit_num']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument limit_num');
        }
        if (!isset($param['goods_ids']) || empty($param['goods_ids']) || !is_array($param['goods_ids'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument goods_ids');
        }
        $param['cid'] = (int)($param['cid']);
        $isTrade      = $param['is_trade'] ?? 0;
        $data         = ['buy_limit' => (int)($param['limit_num']), 'limit_type' => 1, 'md' => time()];
        Goods::whereIn('id', $param['goods_ids'])->where('cid', $param['cid'])->where('is_fast_delivery', 1)->where('is_trade', $isTrade)->where('limit_type', '<>', 2)->update($data);
        return Normal::returnCode(Normal::SUC, '设置成功');
    }

    /**
     * 批量设置商品分类
     * @param array $param
     */
    public function setGoodsClass(array $param) {
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['class_id']) || empty($param['class_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['class_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument class_id');
        }
        if (!isset($param['goods_ids']) || empty($param['goods_ids']) || !is_array($param['goods_ids'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument goods_ids');
        }
        $param['cid'] = (int)($param['cid']);
        $isTrade      = $param['is_trade'] ?? 0;
        $data         = ['class_id' => (int)($param['class_id']), 'md' => time()];
        Goods::whereIn('id', $param['goods_ids'])->where('cid', $param['cid'])->where('is_fast_delivery', 1)->where('is_trade', $isTrade)->update($data);
        //更新ES索引
        ChannelCommodityEsService::instance()->updateIndexByClassId($param['class_id'], $param['cid']);
        return Normal::returnCode(Normal::SUC, '设置成功');
    }

    /**
     * 批量设置预警库存
     * @param array $param
     */
    public function setWarnStorage(array $param) {
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['warn_storage_num']) || empty($param['warn_storage_num']) || (preg_match("/^[1-9]\d*$/", (string)$param['warn_storage_num']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument warn_storage_num');
        }
        if (!isset($param['goods_ids']) || empty($param['goods_ids']) || !is_array($param['goods_ids'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument goods_ids');
        }
        $param['cid'] = (int)($param['cid']);
        $isTrade      = $param['is_trade'] ?? 0;
        $data         = ['warn_storage' => (int)($param['warn_storage_num']), 'md' => time()];
        Goods::whereIn('id', $param['goods_ids'])->where('cid', $param['cid'])->where('is_fast_delivery', 1)->where('is_trade', $isTrade)->update($data);
        return Normal::returnCode(Normal::SUC, '设置成功');
    }

    /**
     * 前置仓商品修改价格模板
     * @param array $param
     */
    public function excelPriceEditTpl(array $param) {
        $param['sp'] = 1;
        $whereRaw    = ChannelCommodityCommonService::instance()->handleWhere($param);
        $sortRaw     = ChannelCommodityCommonService::instance()->handleSort($param);
        $fields      = ['id', 'skucode', 'price_cost', 'price_market', 'price_vip', 'price_store', 'price_recommend', 'price_recommend_vip', 'name', 'barcode', 'is_trade',];
        $list        = Goods::select($fields)->where('is_trade', 0)->whereRaw($whereRaw)->orderByRaw($sortRaw)->get()->toArray();
        $excelTitle  = ['sku', '规格数量', '下游结算价', '推荐会员价', '推荐零售价', '市场价(非必填)', '成本价', '名称', '国际编码'];
        if (!$list) {
            $exportRes = ExportExcelHandle::instance()->uploadAliOssSource('价格导入模板.xlsx', $excelTitle, []);
            if ($exportRes['code'] != Normal::SUC) {
                return Normal::returnCode(Normal::FAIL, $exportRes['msg'] ?? '生成价格模板失败');
            }
            return Normal::returnCode(Normal::SUC, "生成价格模板成功", ['download_url' => $exportRes['data']['path'],]);
        }
        $distributor_level       = DistributorLevel::where('cid', $param['cid'])->orderBy('level', 'asc')->select(['level', 'name'])->get()->toArray();
        $distributor_level_index = array_column($distributor_level, 'name', 'level');
        $goods_ids               = array_column($list, 'id');
        $goodsSpec               = GoodsSpecPrice::whereIn('goods_id', $goods_ids)->orderBy('spec_num', 'asc')->get()->toArray();
        $specBygid               = [];
        if ($goodsSpec) {
            foreach ($goodsSpec as $spec) {
                $specBygid[$spec['goods_id']][] = $spec;
            }
        }
        $hasBatchAll                = GoodsBatch::whereIn('goods_id', $goods_ids)->where('df', 0)->where('type', 0)->get()->toArray();
        $hasBatchAll                = $hasBatchAll ? array_column($hasBatchAll, null, 'goods_id') : [];
        $distributor_level_pric_arr = DistributorPrice::where('cid', $param['cid'])->whereIn('goods_id', $goods_ids)->select(['goods_id', 'price', 'level_id', 'spec_num'])->get();
        $excelData                  = [];
        foreach ($list as $k => $v) {
            $excelData[$k]['skucode'] = $v['skucode'];
            $specList                 = $specBygid[$v['id']] ?? [];
            if (!empty($specList)) {
                $specList            = collect($specList)->sortBy('spec_num')->toArray();
                $specList            = array_column($specList, null, 'spec_num');
                $specNum             = array_column($specList, 'spec_num');
                $spec                = '';
                $price_store         = '';
                $price_recommend_vip = '';
                $price_recommend     = '';
                $price_market        = '';
                $price_cost          = '';
                foreach ($specNum as $item) {
                    $spec                .= $item . ',';
                    $price_store         .= $specList[$item]['price_store'] . ',';
                    $price_recommend_vip .= $specList[$item]['price_recommend_vip'] . ',';
                    $price_recommend     .= $specList[$item]['price_recommend'] . ',';
                    $price_market        .= $specList[$item]['price_market'] . ',';
                    $price_cost          .= $specList[$item]['price_cost'] . ',';
                }
                $excelData[$k]['spec']                = rtrim($spec, ',');
                $excelData[$k]['price_store']         = rtrim($price_store, ',');
                $excelData[$k]['price_recommend_vip'] = rtrim($price_recommend_vip, ',');
                $excelData[$k]['price_recommend']     = rtrim($price_recommend, ',');
                $excelData[$k]['price_market']        = rtrim($price_market, ',');
                $excelData[$k]['price_cost']          = rtrim($price_cost, ',');
            } else {
                if ($v['is_trade'] == 1) {
                    $excelData[$k]['spec'] = 1;
                } else {
                    $has_batch = $hasBatchAll[$v['id']] ?? [];
                    $spec_list = isset($has_batch['spec_list']) && !empty($has_batch['spec_list']) ? json_decode($has_batch['spec_list'], true) : '';
                    $baseSpec  = 1;
                    if (!empty($spec_list)) {
                        $baseSpec = $spec_list[0]['spec_num'] ?? 1;
                    }
                    $excelData[$k]['spec'] = $baseSpec;
                }
                $excelData[$k]['price_store']         = $v['price_store'];
                $excelData[$k]['price_recommend_vip'] = $v['price_recommend_vip'];
                $excelData[$k]['price_recommend']     = $v['price_recommend'];
                $excelData[$k]['price_market']        = $v['price_market'];
                $excelData[$k]['price_cost']          = $v['price_cost'];
            }
            $excelData[$k]['name']    = $v['name'];
            $excelData[$k]['barcode'] = $v['barcode'];
            $distributor_level_price  = $distributor_level_pric_arr->where('goods_id', $v['id'])->toArray();;
            $distributor_level_pric_index = array_column($distributor_level_price, null, 'level_id');
            $new_spec_level_price         = [];
            foreach ($distributor_level_price as $val) {
                $new_spec_level_price[$val['level_id']][$val['spec_num']] = $val['price'];
            }
            foreach ($distributor_level_index as $key => $val) {
                if (!empty($specList)) {
                    $specLevel = '';
                    foreach ($specNum as $item) {
                        $price     = $new_spec_level_price[$key][$item] ?? $specList[$item]['price_store'];
                        $specLevel .= $price . ',';
                    }
                    $excelData[$k][] = rtrim($specLevel, ',');
                } else {
                    if (array_key_exists($key, $new_spec_level_price)) { //设置了等级分销商结算价
                        $excelData[$k][] = $distributor_level_pric_index[$key]['price'];
                    } else {
                        $excelData[$k][] = $v['price_store'];
                    }
                }
            }
        }
        foreach ($distributor_level_index as $v) {
            $excelTitle[] = $v;
        }
        $exportRes = ExportExcelHandle::instance()->uploadAliOssSource('价格导入模板.xlsx', $excelTitle, $excelData);
        if ($exportRes['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $exportRes['msg'] ?? '生成价格模板失败');
        }
        return Normal::returnCode(Normal::SUC, "生成价格模板成功", ['download_url' => $exportRes['data']['path'],]);
    }

    /**
     * 前置仓商品修改商品资料模板
     * @param array $param
     */
    public function excelDetailEditTpl(array $param) {
        $param['sp'] = 1;
        $whereRaw    = ChannelCommodityCommonService::instance()->handleWhere($param);
        $sortRaw     = ChannelCommodityCommonService::instance()->handleSort($param);
        $fields      = ['id', 'skucode', 'class_id', 'name', 'brand_id', 'show_order'];
        $list        = Goods::select($fields)->where('is_trade', 0)->whereRaw($whereRaw)->orderByRaw($sortRaw)->get()->toArray();
        $excelTitle  = ['sku', '商品名称', '商品分类', '品牌', 'b2b排序值（非必填）'];
        if (!$list) {
            $exportRes = ExportExcelHandle::instance()->uploadAliOssSource('修改前置仓商品资料模板.xlsx', $excelTitle, []);
            if ($exportRes['code'] != Normal::SUC) {
                return Normal::returnCode(Normal::FAIL, $exportRes['msg'] ?? '生成修改前置仓商品资料模板失败');
            }
            return Normal::returnCode(Normal::SUC, "生成修改前置仓商品资料模板成功", ['download_url' => $exportRes['data']['path'],]);
        }
        $class_ids  = array_column($list, 'class_id');
        $classIndex = GoodsClass::whereIn('id', $class_ids)->pluck('name', 'id')->toArray();
        $brand_ids  = array_column($list, 'brand_id');
        $brandIndex = GoodsBrand::whereIn('id', $brand_ids)->pluck('name', 'id')->toArray();
        $excelData  = [];
        foreach ($list as $k => $v) {
            $excelData[$k]['skucode'] = $v['skucode'];
            $excelData[$k]['name']    = $v['name'];
            if ($v['class_id'] == 0) {
                $excelData[$k]['class_name'] = '无分类';
            } else {
                $excelData[$k]['class_name'] = $classIndex[$v['class_id']] ?? '无分类';
            }
            $excelData[$k]['brand_name'] = $brandIndex[$v['brand_id']] ?? '';
            $excelData[$k]['show_order'] = $v['show_order'];
        }
        $exportRes = ExportExcelHandle::instance()->uploadAliOssSource('修改前置仓商品资料模板.xlsx', $excelTitle, $excelData);
        if ($exportRes['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $exportRes['msg'] ?? '生成修改前置仓商品资料模板失败');
        }
        return Normal::returnCode(Normal::SUC, "生成修改前置仓商品资料模板成功", ['download_url' => $exportRes['data']['path'],]);
    }

}